import 'package:flutter/material.dart';

void main() => runApp(const MyApp());

class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) => MaterialApp(
        title: '第05课 - 路由与导航',
        theme: ThemeData(useMaterial3: true, colorSchemeSeed: Colors.cyan),
        home: const HomePage(),
        onGenerateRoute: (settings) {
          if (settings.name == '/detail') {
            final item = settings.arguments as String;
            return MaterialPageRoute(builder: (_) => DetailPage(item: item));
          }
          return MaterialPageRoute(
            builder: (_) => const Scaffold(
              body: Center(child: Text('未找到路由')),
            ),
          );
        },
      );
}

class HomePage extends StatelessWidget {
  const HomePage({super.key});
  final items = const ['Apple', 'Banana', 'Cherry', 'Durian'];

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('选择一个水果')),
      body: ListView.builder(
        itemCount: items.length,
        itemBuilder: (context, i) => ListTile(
          title: Text(items[i]),
          trailing: const Icon(Icons.chevron_right),
          onTap: () async {
            final result = await Navigator.pushNamed<String>(
              context,
              '/detail',
              arguments: items[i],
            );
            if (context.mounted && result != null) {
              ScaffoldMessenger.of(context)
                  .showSnackBar(SnackBar(content: Text('你选择了: $result')));
            }
          },
        ),
      ),
    );
  }
}

class DetailPage extends StatelessWidget {
  final String item;
  const DetailPage({super.key, required this.item});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('详情: $item')),
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text('确认选择 $item ?', style: const TextStyle(fontSize: 18)),
            const SizedBox(height: 12),
            ElevatedButton.icon(
              onPressed: () async {
                showDialog(
                  context: context,
                  barrierDismissible: false,
                  builder: (_) => const Center(child: CircularProgressIndicator()),
                );
                await Future.delayed(const Duration(seconds: 1));
                if (context.mounted) {
                  Navigator.of(context).pop(); // 关闭加载指示器
                  Navigator.of(context).pop(item); // 返回并携带结果
                }
              },
              icon: const Icon(Icons.check),
              label: const Text('确认'),
            ),
          ],
        ),
      ),
    );
  }
}